package com.zsl.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.xdevapi.JsonArray;
import com.zsl.dao.UsersDao;
import com.zsl.dao.impl.UsersDaoImpl;
import com.zsl.model.Users;
import com.zsl.service.UsersService;
import com.zsl.util.Base64Encoder;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UsersServiceImpl implements UsersService {

    //依赖注入
    UsersDao usersDao=new UsersDaoImpl();
    @Override
    public Map<String,Object> getAllUser() throws SQLException {
        List<Users> users=usersDao.getAllUser();
        Map<String,Object> result=new HashMap<>();
        JSONArray rows=new JSONArray();
        int total=0;
        if(users.isEmpty()){
            result.put("total",0);
            result.put("rows",new JSONArray());
            return result;
        }
        for(Users user:users){
            Map<String,Object> user_map=new HashMap<>();
            user_map.put("id",user.getId());
            user_map.put("u_name",user.getUsername());
            user_map.put("cellphone",user.getCellphone());
            user_map.put("mobilephone",user.getMobilephone());
            user_map.put("address",user.getAddress());
            user_map.put("email",user.getEmail());
            rows.add(user_map);
            total++;
        }
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    public Users getOneUserById(String id) throws SQLException {
        return null;
    }

    @Override
    public boolean isRealUser(String uname, String pwd) throws SQLException {
        return usersDao.isRealUser(uname,pwd);
    }

    @Override
    public String getIdByName(String name) throws SQLException {
        Users user=usersDao.getUserByName(name);
        return user.getId();
    }

    @Override
    public Map<String, Object> addUsers(Users users) {
        Map<String, Object> result=new HashMap<>();
        //TODO 判断用户输入的合法性

        //TODO 比如，用户名，密码，邮箱需合法

        //TODO 密码加密,同理登录部分也要重新修改

        int line=usersDao.insertUser(users);
        if(line==0){
            result.put("code",0);
            result.put("msg","注册失败");
            return result;
        }
        result.put("code",1);
        result.put("msg","注册成功");
        return result;
    }

    @Override
    public Integer deleteUserById(String user_id) {
        return null;
    }
}
